package cn.ggb.eduservice.service.impl;

import cn.ggb.eduservice.entity.EduSubject;
import cn.ggb.eduservice.entity.excel.SubjectData;
import cn.ggb.eduservice.entity.subject.OneSubject;
import cn.ggb.eduservice.entity.subject.TwoSubject;
import cn.ggb.eduservice.listener.SubjectExcelListener;
import cn.ggb.eduservice.mapper.EduSubjectMapper;
import cn.ggb.eduservice.service.EduSubjectService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-04-01
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            EasyExcel.read(in,SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询出所有的一级分类
        QueryWrapper<EduSubject> oneWrapper = new QueryWrapper<>();
        oneWrapper.eq("parent_id",0);
        List<EduSubject> oneSubjectList = baseMapper.selectList(oneWrapper);

        //查询出所有的二级分类
        QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
        oneWrapper.ne("parent_id",0);
        List<EduSubject> twoSubjectList = baseMapper.selectList(twoWrapper);

        //创建list集合，用于存储最终封装数据
        List<OneSubject> finalSubjectList = new ArrayList<>();

        //对一级分类进行封装
        //循环遍历出一级分类数据，
        for (int i = 0; i <oneSubjectList.size() ; i++) {
            EduSubject eduSubject = oneSubjectList.get(i);
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalSubjectList.add(oneSubject);

            //对二级分类进行封装
            //遍历二级分类
            List<TwoSubject> twoFinalSubjectList = new ArrayList<>();

            for (int m = 0; m < twoSubjectList.size(); m++) {

                EduSubject tSubject = twoSubjectList.get(m);

                if (tSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject);
                    twoFinalSubjectList.add(twoSubject);
                }
            }
            //把一级分类中的二级分类加入到一级分类
            oneSubject.setChildren(twoFinalSubjectList);
        }

        return finalSubjectList;
    }
}
